package util

import (
	"bufio"
	"github.com/xuri/excelize/v2"
	"go.manyji.com/lib/util/convert"
	"io"
	"os"
	"path/filepath"
	"strings"
)

func LoadLines(file io.Reader, walk func(string) error) error {
	br := bufio.NewReader(file)
	for {
		s, _, c := br.ReadLine()
		if c == io.EOF {
			break
		}
		err := walk(string(s))
		if err != nil {
			return err
		}
	}
	return nil
}

func WriteToTxt(dayTime string, taskId, content string) error {
	preDir := GetFilterDir(dayTime)
	AutoCreatePath(preDir)
	fileName := filepath.Join(preDir, taskId+".txt")
	f, err := os.OpenFile(fileName, os.O_RDWR|os.O_CREATE|os.O_APPEND, os.FileMode(0666))
	if err != nil {
		return err
	}
	defer f.Close()
	f.WriteString(content)
	return nil
}
func GetFilterDir(dayTime string) string {
	return filepath.Join(filepath.Dir(os.Args[0]), "../filterTaskFile/", dayTime)
}
func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}
func AutoCreatePath(path string) {
	exist, _ := PathExists(path)
	if !exist {
		os.MkdirAll(path, os.ModePerm)
	}
}

func WriteToExcel(dayTime string, taskId string, list []string) error {
	preDir := GetFilterDir(dayTime)
	AutoCreatePath(preDir)
	fileName := filepath.Join(preDir, taskId+".xlsx")
	categories := map[string]string{"A1": "phone"}
	tagStatus := 0
	if strings.HasPrefix(taskId, "wss") {
		tagStatus = 1
		categories = map[string]string{"A1": "phone", "B1": "sex", "C1": "age", "D1": "pic"}
	}
	xlsx := excelize.NewFile()
	for key, value := range categories {
		xlsx.SetCellValue("Sheet1", key, value)
		_style, err := xlsx.NewStyle(&excelize.Style{
			Fill: excelize.Fill{
				Type:    "pattern",
				Color:   []string{"#EEECE1"},
				Pattern: 1,
			},
			Alignment: &excelize.Alignment{
				Horizontal: "center",
				Vertical:   "center",
			},
			Font: &excelize.Font{
				Bold:   true,
				Family: "宋体",
				Size:   10,
			},
		})
		if err == nil {
			xlsx.SetCellStyle("Sheet1", key, key, _style)
		}
	}
	xlsx.SetColWidth("Sheet1", "A", "D", 15)
	index := 2
	for _, line := range list {
		if tagStatus == 1 {
			lines := strings.SplitN(line, "_", 4)
			xlsx.SetCellValue("Sheet1", "A"+convert.ToString(index), lines[0])
			xlsx.SetCellValue("Sheet1", "B"+convert.ToString(index), lines[1])
			xlsx.SetCellValue("Sheet1", "C"+convert.ToString(index), lines[2])
			xlsx.SetCellValue("Sheet1", "D"+convert.ToString(index), lines[3])
		} else {
			xlsx.SetCellValue("Sheet1", "A"+convert.ToString(index), line)
		}
		index++
	}
	return xlsx.SaveAs(fileName)
}
